#!/bin/bash
#texlive-12many
LIST_NAME=$1
PROJ_NAME=$2
SPEC_NAME=$2.spec

sed -i 's/\r//g' $LIST_NAME
LINE_NUM=$(awk 'END{print NR}' $LIST_NAME)

while [ $LINE_NUM -ne 0 ]
do
  PACKAGE_NAME=`sed -n "$LINE_NUM, 1p" $LIST_NAME | awk -F: '{print $1}'`
  OLD_LICENSE=`sed -n "$LINE_NUM, 1p" $LIST_NAME | awk -F: '{print $2}'`
  NEW_LICENSE=`sed -n "$LINE_NUM, 1p" $LIST_NAME | awk -F: '{print $3}'`
  NEW_LICENSE=`echo ${NEW_LICENSE} | cut -d"^" -f1`

  PKG_LINE_NUM=$(grep -rn "%package -n ${PACKAGE_NAME}$" $SPEC_NAME | awk -F: '{print $1}')
  LICENSE_EXIST="0"
  #LICENSE_NUM=$((PKG_LINE_NUM + 2))
  #LICENSE_INFO=$(sed -n "${LICENSE_NUM}" $SPEC_NAME)
  for increment in $( seq 1 6 )
  do
    LICENSE_NUM=$((PKG_LINE_NUM + $increment))
    LICENSE_INFO=$(sed -n "${LICENSE_NUM}p" $SPEC_NAME)
    if [[ ${LICENSE_INFO} == "License:        ${OLD_LICENSE}" ]];then
      LICENSE_EXIST="1"
      #echo $LICENSE_INFO $LICENSE_NUM 
      if [[ ${NEW_LICENSE} =~ 'follow main' ]];then
        sed -i "${LICENSE_NUM}d" $SPEC_NAME
      else
        sed -i "${LICENSE_NUM}s/${OLD_LICENSE}/${NEW_LICENSE}/" $SPEC_NAME
      fi
    fi
  done

  if [[ ${LICENSE_EXIST} == "0" ]];then
    if [[ ${NEW_LICENSE} =~ 'follow main' ]];then
      echo "do not add license line" > /dev/null
    else
      INSERT_NUM=$((PKG_LINE_NUM + 1))
      sed -i "${INSERT_NUM}a\License:        ${NEW_LICENSE}" $SPEC_NAME
    fi
  fi
  #echo $PKG_LINE_NUM  $PACKAGE_NAME
  LINE_NUM=$((LINE_NUM - 1))
done
